package com.boarsoft.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Enumeration;
import java.util.Properties;

public class PropertiesUtil {
	public static byte[] getBytes(Properties prop, String charset) throws IOException {
		StringBuilder sb = new StringBuilder();
		Enumeration<?> e = prop.propertyNames();
		BufferedWriter bw = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			// prop.store(bos, Util.getStdmfDateTime());
			bw = new BufferedWriter(new OutputStreamWriter(bos, charset));
			bw.newLine();
			// 这里不使用Properties的store()方法，因为冒号会被转义
			while (e.hasMoreElements()) {
				String key = (String) e.nextElement();
				sb.append(key).append("=").append(prop.getProperty(key));
				bw.write(sb.toString());
				bw.newLine();
				sb.setLength(0);
			}
			bw.flush();
			return bos.toByteArray();
		} finally {
			StreamUtil.close(bw);
		}
	}

	public static Properties fromBytes(byte[] ba, String charset) throws IOException {
		Properties prop = new Properties();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(//
					new ByteArrayInputStream(ba), charset));
			prop.load(br);
			return prop;
		} finally {
			StreamUtil.close(br);
		}
	}
}
